define([ "cbui_core","cbui_request", "libex/enc-md5","libex/enc-sha1", "libex/enc-core", "libex/enc-base64", "libex/enc-aes", "libex/enc-rsa"], function(CBUI,Request) {
	//TODO RSA public key 需要与后端java使用的private key一一对应
	var $n = "8291bbce580f3a4a83b4b5b0add2485209edf6e05b05afe446a4ad5898fade77f8e8a3ff675970aed7f9230cc749cfb507a866caf4bb0c5f3b27a300d4cb342904b3a8c292630a123ed1aa70e7d76d88ee4404dc61cdc91a0df831a27e8cbd4c9442efa894fb80d8d8a3290a717852324eea845406ced25e827e7427535f164b";
	var $e = "10001";
	// 需要与后端java使用的IV一一对应
	var $iv = '0102030405060708';
	var $aes_key_len = 16;
	var rsa = new RSAKey();
	rsa.setPublic($n, $e);
	
	var Fn = CBUI.Fn;
	var Ex = Fn.ex;
	// 替换doTrans 方法
	CBUI.Browser.doTrans = function(callback, oldPage, newPage, direction, duration) {
		/*newPage.show();
		newPage.css({visibility: "visible"});
		if (direction === -1) {
			oldPage.remove();
		} else {
			oldPage.hide();
		}*/
		setTimeout(function(){CBUI.Fn.safeCall(callback);},200);
	};
	
	var _fetch = Request.prototype.fetch;
	Request.prototype.fetch = function() {
		var url = this.request.url;
		if (_.string.startsWith(url, "client:///")) {
			// 客户端类请求，忽略
			// exec.call(this);
			_fetch.call(this);
		} else {
			var self = this;
			var data = self.request.data;	
			data = JSON.stringify(data);
			data = CryptoJS.enc.Utf8.parse(data);
			
			// genAESKey
			var AESKeyStr = genAESKey($aes_key_len);
			var AESKeyHex = CryptoJS.enc.Utf8.parse(AESKeyStr);
			// AES encode data
			var iv = CryptoJS.enc.Utf8.parse($iv);
			//AESData 16的整数倍
			for(var i=0; i < 3;i++){
				var AESData = CryptoJS.AES.encrypt(data, AESKeyHex, {
					iv : iv,
					mode : CryptoJS.mode.CBC
				});
				if(AESData%16 === 0){
					break;
				}
			}
			// RSA encode AES KEY   长度为256
			
			for(var i=0; i < 3;i++){
				var AESKeyByRsa = rsa.encrypt(AESKeyStr);
				if(AESKeyByRsa.length == 256){
					break;
				}
			}
			// data + key
			data = AESData + AESKeyByRsa;
			
			var postData = data;
			$.ajax({
				type : 'post',
				url : self.request.url,
				data : postData,
				dataType : "json",
				success : function(response) {
					self.complete(response);
				},
				error : function(e) {
					console.error(e);
				}
			});
		}
	};
});

/**
 * 随机AES KEY
 * 
 * @returns {String}
 */
function genAESKey(len) {
	var toforkey = "";
	var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split("");
	var index;
	for (var i = 0; i < len; i++) {
		index = Math.ceil(Math.random() * 64);
		toforkey += e[index - 1];
	}
	return toforkey;
}